package com.atguigu.mySmartCampus.util;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CreateVerifyCodeImg{

    private static int WIDTH =90;
    private static int HEIGHT = 30;
    private static int FONT_SIZE =20;
    private static char[] VERIFY_CODE;
    private static BufferedImage VERIFY_CODE_IMAGE;

    public static BufferedImage getVerifyCodeImg(){
        VERIFY_CODE_IMAGE = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_BGR);
        Graphics graphics = VERIFY_CODE_IMAGE.getGraphics();
        VERIFY_CODE = generateVerifyCode();
        drawBackground(graphics);
        drawRands(graphics, VERIFY_CODE);
        //dispose 安排
        graphics.dispose();
        return VERIFY_CODE_IMAGE;
    }

    public static char[] getVerifyCode(){
        return VERIFY_CODE;
    }

    private static char[] generateVerifyCode(){
        String chars  = "0123456789abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] fourVerifyCode =new char[4];
        for(int i =0 ;i < 4 ;i++){
            int rand = (int)(Math.random()*(10+26+26));
            fourVerifyCode[i] = chars.charAt(rand);
        }
        return fourVerifyCode;
    }

    //fillRect 填充
    //oval 椭圆
    private static void drawBackground(Graphics graphics){
         graphics.setColor(Color.white); 
         
         graphics.fillRect(0,0, WIDTH, HEIGHT);
         //绘制干扰点
         for(int i = 0; i <200 ; i++){
            int x = (int)(Math.random()* WIDTH);
            int y = (int)(Math.random()* HEIGHT);
            graphics.setColor(getRandomColor());
            //坐标xy+宽高
            graphics.drawOval(x,y,1,1);
         }
    }

    //绘制验证码
    public static void drawRands(Graphics graphics,char[] fourVerifyCode){
        Font font = new Font("console",Font.BOLD, FONT_SIZE);
        graphics.setFont(font);
        for(int i = 0;i < fourVerifyCode.length; i++){
            graphics.setColor(getRandomColor());
            //参数drawString, drawFont, drawBrush画笔 这里应该没用到 下面只有三个参数 int应该是坐标, drawPoint
            graphics.drawString(""+fourVerifyCode[i], i*FONT_SIZE+10,25);
        }
    }

    private static Color getRandomColor(){
        //util.Random  网上说短期内的随机数是同一个
        Random  random = new Random();
        //RGB颜色模式的数值为0-255
        Color color = new Color(random.nextInt(220),random.nextInt(220),random.nextInt(220));
        return color;
    } 
}